package backed.controller;

import backed.dto.PublishRequest;
import backed.entity.SecondHandItem;
import backed.repository.UserRepository;
import backed.service.FileUploadService;
import backed.service.SecondHandItemService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.regex.Pattern;
import org.springframework.data.domain.Page;

@Tag(name = "二手商品管理", description = "提供二手商品的发布、查询、更新、删除和图片上传等功能")
@RestController
@RequestMapping("/api/item/")
@CrossOrigin
public class SecondHandItemController {
    @Autowired
    private SecondHandItemService secondHandItemService;
    
    @Autowired
    private FileUploadService fileUploadService;

    @Autowired
    private UserRepository userRepository;
    
    // 图片格式正则表达式
    private final Pattern IMAGE_PATTERN = Pattern.compile("(?i).*\\.(jpg|jpeg|png|gif|webp)$");

    @Operation(summary = "发布二手商品", description = "用户发布新的二手商品信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "发布成功", 
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = Map.class))),
            @ApiResponse(responseCode = "400", description = "参数错误或发布失败")
    })
    @Parameters({
            @Parameter(name = "params", description = "商品信息参数", 
                    schema = @Schema(example = "{\"userId\":\"1\",\"title\":\"二手笔记本电脑\",\"description\":\"九成新，性能良好\",\"price\":\"3999.00\",\"conditionLevel\":\"九成新\",\"category\":\"电子产品\",\"images\":\"/uploads/images/123456.jpg\"}"))
    })
    @PostMapping("/publish")
    public Map<String, Object> publish(@Valid @RequestBody PublishRequest publishRequest) {
        Map<String, Object> result = new HashMap<>();



        Long userId = publishRequest.getUserId();
        Double price = publishRequest.getPrice();
        String title = publishRequest.getTitle();
        String description = publishRequest.getDescription();
        String conditionLevel = publishRequest.getConditionLevel();
        String category = publishRequest.getCategory();
        String images = publishRequest.getImages();



        if(userId == null){
            result.put("success", "false");
            result.put("message","用户id不能为空。");
            return result;
        }
        boolean exists = userRepository.existsById(userId);
        if (!exists) {
            result.put("success", "false");
            result.put("message", "用户不存在，请重新登录或检查 userId！");
            return result;
        }

        if(title == null){
            result.put("success", "false");
            result.put("message","标题不能为空。");
            return result;
        }
        if(price == null){
            result.put("success", "false");
            result.put("message","价格不能为空。");
            return result;
        }


        SecondHandItem publishedItem = secondHandItemService.publish(userId, title, description, price, conditionLevel, category, images);


        Map<String, Object> data = new HashMap<>();
        data.put("itemId", publishedItem.getId());
        data.put("title", publishedItem.getTitle());
        data.put("price", publishedItem.getPrice());
        data.put("conditionLevel", publishedItem.getConditionLevel());
        data.put("category", publishedItem.getCategory());
        result.put("message", "商品发布成功");
        result.put("data", data);

        return result;
    }

    @Operation(summary = "获取用户发布的商品列表", description = "查询指定用户发布的所有二手商品")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功", 
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = Map.class))),
            @ApiResponse(responseCode = "400", description = "参数错误")
    })
    @Parameter(name = "userId", description = "用户ID", required = true, example = "1")
    @GetMapping("/my-items")
    public Map<String, Object> getUserItems(@RequestParam Long userId) {
        Map<String, Object> result = new HashMap<>();

        // 参数校验
        if (userId == null) {
            result.put("success", false);
            result.put("message", "缺少必要参数userId");
            result.put("data", null);
            return result;
        }


        List<SecondHandItem> itemList;
        itemList = secondHandItemService.getUserItems(userId);



        List<Map<String,Object>> itemDataList = new ArrayList<>();

        for (SecondHandItem item : itemList) {
            Map<String, Object> itemData = new HashMap<>();
            itemData.put("id", item.getId());
            itemData.put("title", item.getTitle());
            itemData.put("price", item.getPrice());
            itemData.put("conditionLevel", item.getConditionLevel());
            itemData.put("category", item.getCategory());
            itemData.put("status", item.getStatus());
            itemData.put("viewCount", item.getViewCount());
            itemDataList.add(itemData);
        }

        result.put("success", true);
        result.put("message", "获取用户商品列表成功");
        result.put("data", new HashMap<String, Object>() {
            {
                put("items", itemDataList);
                put("total", itemDataList.size());
            }
        });

        return result;
    }

    @Operation(summary = "获取商品列表", description = "分页查询二手商品列表，支持分类和关键词搜索")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功", 
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = Map.class))),
            @ApiResponse(responseCode = "400", description = "参数错误")
    })
    @Parameters({
            @Parameter(name = "category", description = "商品分类（可选）", example = "电子产品"),
            @Parameter(name = "keyword", description = "搜索关键词（可选）", example = "笔记本"),
            @Parameter(name = "page", description = "页码，默认为1", example = "1"),
            @Parameter(name = "size", description = "每页数量，默认为10", example = "10")
    })
    @GetMapping("/list")
    public Map<String, Object> getItemsList(
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        Map<String, Object> result = new HashMap<>();

        // 参数校验
        if (page == null || page <= 0) {
            page = 1;
        }
        if (size == null || size <= 0 || size > 100) {
            size = 10;
        }

        // 调用服务层方法获取商品列表
        Page<SecondHandItem> itemsPage = secondHandItemService.getItemsList(category, keyword, page, size);
        List<SecondHandItem> itemsList = itemsPage.getContent();
        long total = itemsPage.getTotalElements();

        // 构建返回数据
        List<Map<String, Object>> itemsDataList = new ArrayList<>();
        for (SecondHandItem item : itemsList) {
            Map<String, Object> itemData = new HashMap<>();
            itemData.put("id", item.getId());
            itemData.put("title", item.getTitle());
            itemData.put("price", item.getPrice());
            itemData.put("conditionLevel", item.getConditionLevel());
            itemData.put("category", item.getCategory());
            itemData.put("images", item.getImages());
            itemData.put("viewCount", item.getViewCount());
            itemData.put("status", item.getStatus());
            itemsDataList.add(itemData);
        }

        result.put("success", true);
        result.put("message", "获取商品列表成功");
        result.put("data", new HashMap<String, Object>() {
            {
                put("total", total);
                put("items", itemsDataList);
            }
        });

        return result;
    }

    @Operation(summary = "获取商品详情", description = "根据商品ID查询二手商品的详细信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功", 
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = Map.class))),
            @ApiResponse(responseCode = "404", description = "商品不存在")
    })
    @Parameter(name = "id", description = "商品ID", required = true, example = "1")
    @GetMapping("/detail/{id}")
    public Map<String, Object> getItemDetails(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        SecondHandItem item = secondHandItemService.getItemInfo(id);
        
        // 构建data对象
        Map<String, Object> data = new HashMap<>();
        data.put("id", item.getId());
        data.put("userId", item.getUserId());
        data.put("title", item.getTitle());
        data.put("description", item.getDescription());
        data.put("price", item.getPrice());
        data.put("conditionLevel", item.getConditionLevel());
        data.put("category", item.getCategory());
        data.put("images", item.getImages());
        data.put("viewCount", item.getViewCount());
        
        // 组装返回结果
        result.put("success", true);
        result.put("data", data);

        
        return result;
    }

    @Operation(summary = "更新商品信息", description = "修改现有二手商品的信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "更新成功", 
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = Map.class))),
            @ApiResponse(responseCode = "400", description = "参数错误"),
            @ApiResponse(responseCode = "404", description = "商品不存在")
    })
    @Parameters({
            @Parameter(name = "id", description = "商品ID", required = true, example = "1"),
            @Parameter(name = "updateitem", description = "更新后的商品信息", required = true)
    })
    @PutMapping("/update/{id}")
    public Map<String, Object> updateItem(@PathVariable Long id, @RequestBody SecondHandItem updateitem) {
        Map<String, Object> result = new HashMap<>();
        
        // 验证参数
        if (id == null) {
            result.put("success", false);
            result.put("message", "商品ID不能为空");
            return result;
        }
        
        if (updateitem == null) {
            result.put("success", false);
            result.put("message", "更新数据不能为空");
            return result;
        }
        
        // 使用URL路径中的id获取商品信息
        SecondHandItem item = secondHandItemService.getItemInfo(id);
        
        // 检查商品是否存在
        if (item == null) {
            result.put("success", false);
            result.put("message", "商品不存在");
            return result;
        }
      if (updateitem.getTitle()!=null){item.setTitle(updateitem.getTitle());}
      if (updateitem.getDescription()!=null){item.setDescription(updateitem.getDescription());}
      if (updateitem.getPrice()!=null){item.setPrice(updateitem.getPrice());}
      if (updateitem.getConditionLevel()!=null){item.setConditionLevel(updateitem.getConditionLevel());}
      if (updateitem.getCategory()!=null){item.setCategory(updateitem.getCategory());}
      if (updateitem.getImages()!=null){item.setImages(updateitem.getImages());}
      if (updateitem.getViewCount()!=null){item.setViewCount(updateitem.getViewCount());}

      SecondHandItem savedSecondHandItem = secondHandItemService.update(item);
      if (savedSecondHandItem != null) {
          result.put("success", true);
          result.put("message","更新成功");

          Map<String, Object> data = new HashMap<>();
          data.put("id", savedSecondHandItem.getId());
          data.put("userId", savedSecondHandItem.getUserId());
          data.put("title", savedSecondHandItem.getTitle());
          data.put("description", savedSecondHandItem.getDescription());
          data.put("price", savedSecondHandItem.getPrice());
          data.put("conditionLevel", savedSecondHandItem.getConditionLevel());
          data.put("category", savedSecondHandItem.getCategory());
          data.put("images", savedSecondHandItem.getImages());
          data.put("viewCount", savedSecondHandItem.getViewCount());
          data.put("status", savedSecondHandItem.getStatus());
          result.put("data", data);
      }

      else {
          result.put("success", false);
          result.put("message","更新失败");
      }
      return result;
    }

    @Operation(summary = "删除商品", description = "根据商品ID删除二手商品")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "删除成功", 
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = Map.class))),
            @ApiResponse(responseCode = "400", description = "参数错误"),
            @ApiResponse(responseCode = "404", description = "商品不存在")
    })
    @Parameter(name = "id", description = "商品ID", required = true, example = "1")
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> deleteItem(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        

        if (id == null) {
            result.put("success", false);
            result.put("message", "缺少必要参数id");
            return result;
        }
        

        SecondHandItem item = secondHandItemService.getItemInfo(id);
        if (item == null) {
            result.put("success", false);
            result.put("message", "商品不存在");
            return result;
        }
        

        boolean deleteResult = secondHandItemService.deleteItem(id);
        if (deleteResult) {
            result.put("success", true);
            result.put("message", "删除成功");
        } else {
            result.put("success", false);
            result.put("message", "删除失败");
        }
        
        return result;
    }

    @Operation(summary = "上传商品图片", description = "上传二手商品的图片文件到腾讯云COS，支持jpg、jpeg、png、gif、webp格式，最大10MB")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "上传成功", 
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = Map.class))),
            @ApiResponse(responseCode = "400", description = "文件格式错误或大小超限"),
            @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @Parameters({
            @Parameter(name = "file", description = "图片文件", required = true, 
                    schema = @Schema(type = "string", format = "binary")),
            @Parameter(name = "userId", description = "用户ID", required = true, example = "1")
    })
    @PostMapping("/upload-image")
    public Map<String, Object> uploadImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam("userId") Long userId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 1. 参数校验 - 检查文件是否为空
            if (file == null || file.isEmpty()) {
                result.put("success", false);
                result.put("message", "文件为空，请选择图片上传");
                return result;
            }
            
            // 2. 参数校验 - 检查用户ID
            if (userId == null) {
                result.put("success", false);
                result.put("message", "用户ID不能为空");
                return result;
            }
            
            // 3. 文件大小验证 - 限制10MB
            if (file.getSize() > 10 * 1024 * 1024) {
                result.put("success", false);
                result.put("message", "文件大小不能超过10MB");
                return result;
            }
            
            // 4. 文件类型验证 - 检查文件名和MIME类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || !IMAGE_PATTERN.matcher(originalFilename).matches()) {
                result.put("success", false);
                result.put("message", "不支持的图片格式，仅支持jpg、jpeg、png、gif、webp格式");
                return result;
            }
            
            // 额外的MIME类型验证
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                result.put("success", false);
                result.put("message", "文件不是有效的图片类型");
                return result;
            }
            
            // 5. 使用FileUploadService上传到腾讯云COS
            String fileUrl = fileUploadService.uploadFile(file, userId);
            
            // 6. 从URL中提取文件名（用于返回）
            String filename = originalFilename;
            if (fileUrl != null && fileUrl.contains("/")) {
                filename = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
            }
            
            // 7. 构建成功响应
            Map<String, Object> data = new HashMap<>();
            data.put("url", fileUrl);
            data.put("filename", filename);
            data.put("size", file.getSize());
            
            result.put("success", true);
            result.put("data", data);
            result.put("message", "图片上传成功");
            
            return result;
            
        } catch (IllegalArgumentException e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            return result;
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "上传失败: " + e.getMessage());
            return result;
        }
    }
}

